package dao;

import com.alibaba.fastjson.JSON;
import domin.Library;
import lombok.extern.slf4j.Slf4j;
import util.CommonDao;
import util.Condition;
import util.JdbcHelper;
import util.Pagination;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;
import java.util.TreeSet;

@Slf4j
public class LibraryDao {
    private static LibraryDao libraryDao = new LibraryDao();
    private LibraryDao(){}
    public static LibraryDao getInstance(){
        return libraryDao;
    }
    PreparedStatement preparedStatement = null;
    ResultSet resultSet = null;
    public Library find (Connection connection , int id) throws SQLException {
        PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM library where id=?");
        preparedStatement.setInt(1,id);
        ResultSet resultSet = preparedStatement.executeQuery();
        Library library = null;
        if (resultSet.next()){
            library= new Library();
            library.setId(resultSet.getInt("id"));
            library.setno(resultSet.getString("no"));
            library.setname(resultSet.getString("name"));
            library.setremarks (resultSet.getString("remarks")) ;
        }
        JdbcHelper.close(resultSet,preparedStatement);
        return library;
    }
    public Collection<Library> findAll(Connection connection, Collection<Condition> condition, Pagination pagination) throws SQLException {
        Collection<Library> libraries = new TreeSet<Library>();
        int totalNum = CommonDao.getInstance().count(connection, "library");
        String sql_select_all = "SELECT * FROM library ";
        if (condition != null) {
            sql_select_all += Condition.toWhereClause(JSON.toJSONString(condition));
            log.trace(sql_select_all);
        }
        if (pagination != null) {
            sql_select_all += pagination.toLimitClause(totalNum);
            log.trace(sql_select_all);
        }
        this.preparedStatement = connection.prepareStatement(sql_select_all);
        this.resultSet = preparedStatement.executeQuery();
        while (this.resultSet.next()) {
            int id = resultSet.getInt("id");
            String no = resultSet.getString("no");
            String name = resultSet.getString("name");
            String remarks = resultSet.getString("remarks");
            Library foundLibraries = new Library(id, no, name,remarks);
            libraries.add(foundLibraries);
        }
        JdbcHelper.close(this.resultSet, this.preparedStatement);
        return libraries;
    }
}